package com.qf.web.servlet;

import cn.dsna.util.images.ValidateCode;
import com.qf.domain.Address;
import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;
import com.qf.utils.RandomUtils;
import com.qf.utils.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/*
 *                             _ooOoo_
 *                            o8888888o
 *                            88" . "88
 *                            (| -_- |)
 *                            O\  =  /O
 *                         ____/`---'\____
 *                       .'  \\|     |//  `.
 *                      /  \\|||  :  |||//  \
 *                     /  _||||| -:- |||||-  \
 *                     |   | \\\  -  /// |   |
 *                     | \_|  ''\---/''  |   |
 *                     \  .-\__  `-`  ___/-. /
 *                   ___`. .'  /--.--\  `. . __
 *                ."" '<  `.___\_<|>_/___.'  >'"".
 *               | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *               \  \ `-.   \_ __\ /__ _/   .-` /  /
 *          ======`-.____`-.___\_____/___.-`____.-'======
 *                             `=---='
 *          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *                     佛祖保佑        永无BUG
 *            佛曰:
 *                   写字楼里写字间，写字间里程序员；
 *                   程序人员写程序，又拿程序换酒钱。
 *                   酒醒只在网上坐，酒醉还来网下眠；
 *                   酒醉酒醒日复日，网上网下年复年。
 *                   但愿老死电脑间，不愿鞠躬老板前；
 *                   奔驰宝马贵者趣，公交自行程序员。
 *                   别人笑我忒疯癫，我笑自己命太贱；
 *                   不见满街漂亮妹，哪个归得程序员？
 */
@WebServlet(name = "UserServlet",value = "/userservlet")
public class UserServlet extends BaseServlet {

    //注册
    public String register(HttpServletRequest request,HttpServletResponse response){

        //1获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        //2校验
        //用户名
        if(StringUtils.empty(username)){
            request.setAttribute("registerMsg", "用户名不能为空");
            return "/register.jsp";
        }
        if(StringUtils.empty(password)){
            request.setAttribute("registerMsg", "密码不能为空");
            return "/register.jsp";
        }
        if(password.length()<6||password.length()>12){
            request.setAttribute("registerMsg", "密码长度不符合要求");
            return "/register.jsp";
        }
        if(!password.equals(repassword)){
            request.setAttribute("registerMsg", "两次密码不一致");
            return "/register.jsp";
        }
        if(StringUtils.empty(email)){
            request.setAttribute("registerMsg", "邮箱不能为空");
            return "/register.jsp";
        }
        //邮箱格式

        //3创建用户对象
        User user=new User(0, username, password, email, gender, 0, 1, RandomUtils.createActive());
        //4创建业务对象
        UserService userService=new UserServiceImpl();
        //5调用方法
        try {
            userService.regist(user);
            return "redirect:/registerSuccess.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("registerMsg", "注册失败:"+e.getMessage());
            return "/register.jsp";
        }

    }

    public String login(HttpServletRequest request,HttpServletResponse response){
        //获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode=request.getParameter("vcode");
        String auto=request.getParameter("auto");
        String code = (String) request.getSession().getAttribute("code");


        //校验
        if(StringUtils.empty(username)){
            request.setAttribute("msg", "用户名不能为空");
            return "/login.jsp";
        }
        if(StringUtils.empty(password)){
            request.setAttribute("msg", "密码不能为空");
            return "/login.jsp";
        }
        if(StringUtils.empty(vcode)){
            request.setAttribute("msg", "验证码不能为空");
            return "/login.jsp";
        }
        if(!vcode.equalsIgnoreCase(code)){
            request.setAttribute("msg", "验证码错误");
            return "/login.jsp";
        }

        //创建业务对象
        UserService userService=new UserServiceImpl();
        try {
            User user=userService.login(username, password);
            if(user!=null) {
                //成功
                if(auto!=null){
                    String userinfo=username+"#"+password;
                    userinfo= Base64Utils.encode(userinfo);
                    Cookie cookie=new Cookie("userinfo",userinfo );
                    cookie.setMaxAge(60*60*24*14);
                    cookie.setPath(request.getContextPath());
                    cookie.setHttpOnly(true);
                    response.addCookie(cookie);
                }else{
                    Cookie cookie=new Cookie("userinfo","" );
                    cookie.setMaxAge(0);
                    cookie.setPath(request.getContextPath());
                    cookie.setHttpOnly(true);
                    response.addCookie(cookie);
                }
                request.getSession().setAttribute("user", user);

                return "redirect:/index.jsp";
            }else{
                request.setAttribute("msg","用户名或密码错误");
                return "/login.jsp";
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", e.getMessage());
            return "/login.jsp";
        }
    }

    public String checkUserName(HttpServletRequest request,HttpServletResponse response) throws Exception{
        String username = request.getParameter("username");
        if(StringUtils.empty(username)){
            response.getWriter().write("1");
            return null;
        }
        UserService userService=new UserServiceImpl();
        boolean b=userService.checkUserName(username);
        if(b){
            response.getWriter().write("1");//1 表示存在
        }else{
            response.getWriter().write("0");//0 表示不存在
        }
        return null;
    }

    public String code(HttpServletRequest request,HttpServletResponse response) throws Exception{

        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control","no-cache" );
        response.setHeader("Pragma", "no-cache");

        ValidateCode validateCode=new ValidateCode(120, 30, 4,30 );
        String code = validateCode.getCode();
        request.getSession().setAttribute("code", code);
        validateCode.write(response.getOutputStream());
        return null;

    }

    public String logOut(HttpServletRequest request,HttpServletResponse response) throws  Exception{
        request.getSession().removeAttribute("user");
        Cookie cookie=new Cookie("userinfo", "");
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        request.getSession().invalidate();
        return "redirect:/index.jsp";
    }

    public String getAddress(HttpServletRequest request,HttpServletResponse response) throws Exception{
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }
        UserService userService=new UserServiceImpl();
        try {
            List<Address> addList = userService.findAddress(user.getId());
            System.out.println(addList.toString());
            request.setAttribute("addList", addList);
            return "/self_info.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "获取地址失败");
            return "/message.jsp";
        }

    }

    public String addAddress(HttpServletRequest request,HttpServletResponse response) throws Exception{
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        if(StringUtils.empty(name)){
            request.setAttribute("msg", "收件人不能为空");
            return "/self_info.jsp";
        }
        if(StringUtils.empty(phone)){
            request.setAttribute("msg", "电话不能为空");
            return "/self_info.jsp";
        }
        if(StringUtils.empty(detail)){
            request.setAttribute("msg", "详细地址不能为空");
            return "/self_info.jsp";
        }

        UserService userService=new UserServiceImpl();
        try {
            Address address=new Address(0, detail, name, phone,user.getId() , 0);
            userService.addAddress(address);
            return  "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "添加失败");
            return "/self_info.jsp";
        }
    }


    public String defaultAddress(HttpServletRequest request,HttpServletResponse response) throws Exception{
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");
        if(StringUtils.empty(id)){
            return null;
        }
        UserService userService=new UserServiceImpl();
        try {
            userService.updateAddStatus(user.getId(),Integer.parseInt(id));
            return  "redirect:/userservlet?method=getAddress";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("msg", "更新默认地址失败");
            return "/self_info.jsp";
        }

    }

    public String updateAddress(HttpServletRequest request,HttpServletResponse response) throws Exception{
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");
        String level = request.getParameter("level");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        response.setContentType("text/html;charset=utf-8");
        if(StringUtils.empty(id)){
            response.getWriter().write("<script>alert('id不能为空');</script>");
            return null;
        }
        if(StringUtils.empty(level)){
            response.getWriter().write("<script>alert('地址状态不能为空'); window.location='userservlet?method=getAddress';</script>");
            return null;
        }

        if(StringUtils.empty(name)){
            response.getWriter().write("<script>alert('姓名不能为空');window.location='userservlet?method=getAddress';</script>");
            return null;
        }
        if(StringUtils.empty(phone)){
            response.getWriter().write("<script>alert('电话不能为空');window.location='userservlet?method=getAddress';</script>");
            return null;
        }
        if(StringUtils.empty(phone)){
            response.getWriter().write("<script>alert('详细地址不能为空');window.location='userservlet?method=getAddress';</script>");
            return null;
        }

        try {
            Address address=new Address(Integer.parseInt(id), detail, name, phone, user.getId(),Integer.parseInt(level) );
            UserService userService=new UserServiceImpl();
            userService.updateAdd(address);

            return "redirect:/userservlet?method=getAddress";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.getWriter().write("<script>alert('更新地址失败');window.location='userservlet?method=getAddress';</script>");
            return null;
        }
    }


    public String deleteAddress(HttpServletRequest request, HttpServletResponse response) throws Exception{
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");
        response.setContentType("text/html;charset=utf-8");
        if(StringUtils.empty(id)){
            response.getWriter().write("<script>alert('id不能为空');</script>");
            return null;
        }
        UserService userService=new UserServiceImpl();
        try {
            userService.deleteAddress(Integer.parseInt(id));
            return "redirect:/userservlet?method=getAddress";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.getWriter().write("<script>alert('删除地址失败');window.location='userservlet?method=getAddress';</script>");
            return null;
        }
    }
}
